﻿var Home = function() {
    return {
        notification: null,
        resized:true,
        Init: function () {
            Home.search();
        },
        closetab: function (name) {
            var isExists = false;
            var tabIndex = 0;
            name = "tab" + name;
            $("div#tabs ul li ").each(function (index, element) {
                if (element.attributes.length > 0 && element.attributes["aria-controls"].value != undefined) {
                    var text = element.attributes["aria-controls"].value;
                    if (text == name) {
                        var parent = element.parentElement;
                        parent.children[index].remove();
                        isExists = true;
                        tabIndex = index;
                        $("#" + name).remove();
                        $("div#tabs").tabs({ active: tabIndex-1 });
                    }
                }                
            });
        },
        CreateGrid: function (data) {
            var entity, currency, country, managedBy, investmentDesk, dataLoad, approvedDate, latestDataDate, contains, partOfGroup = null;
            if ($("#entityType").val() == undefined || $("#entityType").val() == -1) {
                entity = null;
            }
            else {
                entity = $("#entityType").val();
            }
            if ($("#currency").val() == undefined || $("#currency").val() == -1) {
                entity = null;
            }
            else {
                currency = $("#currency").val();
            }
            if ($("#country").val() == undefined || $("#country").val() == -1) {
                country = null;
            }
            else {
                country = $("#country").val();
            }
            if ($("#managedBy").val() == undefined || $("#managedBy").val() == -1) {
                managedBy = null;
            }
            else {
                managedBy = $("#managedBy").val();
            }
            if ($("#investmentDesk").val() == undefined || $("#investmentDesk").val() == -1) {
                investmentDesk = null;
            }
            else {
                investmentDesk = $("#investmentDesk").val();
            }
            if ($("#dataLoadType").val() == undefined || $("#dataLoadType").val() == -1) {
                dataLoad = null;
            }
            else {
                dataLoad = $("#dataLoadType").val();
            }
            approvedDate = $("#approvedDate").data("kendoDatePicker").value();
            latestDataDate = $("#latestDataDate").data("kendoDatePicker").value();

            if ($("#searchContains").val() == undefined || $("#searchContains").val() == -1) {
                contains = null;
            }
            else {
                contains = $("#searchContains").val();
            }
            if ($("#partOfGroup").val() == undefined || $("#partOfGroup").val() == -1) {
                partOfGroup = null;
            }
            else {
                partOfGroup = $("#partOfGroup").val();
            }
            $("#grid").kendoGrid(
                {
                    dataSource: {
                        transport:
                                    {
                                        read: {
                                            type: "POST",
                                            dataType: "json",
                                            url: "GetGriData",
                                            data: {
                                                EntityType: entity,
                                                Currency: currency,
                                                Country: country,
                                                ManagedBy: managedBy,
                                                InvestmentDesk: investmentDesk,
                                                DataLoad: dataLoad,
                                                ApprovedDate:approvedDate,
                                                LatestData: latestDataDate,
                                                Contains: contains,
                                                PartOfGroup:partOfGroup
                                            }
                                        }
                                    },
                        pageSize: 7,
                    },
                height:400,
                groupable: true,
                sortable: true,
                resizable: true,
                selectable: true,
                scrollable:true,
                dataBound: function (e) {
                    $(".k-grid-content tbody tr").click(function () {
                        $("#rightbar").show();
                        $("#viewPortfolioContainer").show();
                        $("#viewPortfolio").animate({ 'margin-top': '7px' }, 1000);
                    });
                },
                columnShow: function (e) {
                    //this.wrapper.width(grid.wrapper.width() + e.column.width);
                },
                pageable: {
                    refresh: true,
                    pageSizes: true
                },
                columns: [{
                    field: "portfolioId",
                    hidden:true
                },
                {
                    field: "Name",
                    width: 135,
                    title: "Name"
                },                
                {
                    field: "Code",
                    width: 55,
                    title: "Code"
                },
                {
                    field: "EntityType",
                    width: 85,
                    title: "Entity Name"
                },
                {
                    field: "Currency",
                    width: 60,
                    title: "Currency"
                },
                {
                    field: "Country",
                    width: 60,
                    title: "Country"
                },
                {
                    field: "FundManager",
                    width: 100,
                    title: "Fund Manager"
                },
                {
                    field: "InvestmentDesk",
                    width: 90,
                    title: "Investment Desk"
                },
                {
                    field: "AssetClass",
                    width: 90,
                    title: "Asset Class"
                },                
                {
                    field: "DataLoad",
                    width: 90,
                    title: "Data Load Type"
                },
                {
                    field: "ApprovedDate",
                    width: 90,
                    title: "Approved Date"
                }
                ]
                });
        },
        addtab: function (e) {
            var isExists = false;
            var name = e.textContent;
            var tabIndex = 0;
            $("div#tabs ul li a").each(function (index, element) {
                var text = element.text;
                if (text == name) {
                    isExists = true;
                    tabIndex = index;
                }
            });

            if (!isExists) {
                var num_tabs = $("div#tabs ul li a").length;
                $("div#tabs ul").first().append("<li ><a href='#tab" + e.id + "'>" + e.textContent + "</a><span onclick=\"" + "Home.closetab('" + e.id + "')\"" + "class=\"" + "ui-icon " + "ui-icon-circle-close\"" + "></span></li>");
                $("div#tabs").append("<div id='tab" + e.id + "' class=\"" + "tabwidth\"+></div>");
                $("div#tabs").tabs("refresh");
                $("div#tabs").tabs({ active: num_tabs });

                $.ajax({
                    type: "post",
                    url: "GetPortfolio",
                    cache: false,
                    success: function (data) {
                        $("#tab" + e.id).html(data);
                    }
                });
            }
            else {
                $("div#tabs").tabs({ active: tabIndex });
            }
        },

        search: function () {
            $("#searchEntity").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "GetEntities",
                        type: "POST",
                    dataType: "json",
                    data: { "request": request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label : item,value:item.Entity};
                        }))

                    }
                })
            }
        }).data("ui-autocomplete")._renderItem = function (ul, item) {
        var label = item.label.Entity + item.label.EntityDesc + item.label.EntityType;
        var re = new RegExp("(" + this.term + ")", "gi"),
                        cls = "search-text-highlight",
                       template = "<span class='" + cls + "'>$1</span>";
        var labelEntity = item.label.Entity.replace(re, template);
        var labelEntityDesc = item.label.EntityDesc.replace(re, template);
        var labelEntityType = item.label.EntityType.replace(re, template);
        var $li = $("<li/>").appendTo(ul);
                
        $("<a/>").attr("href", "#")
                   .html("<div style=\"width:330px;\"><div style=\"width:70px;display:inline-block;text-align:top;\">" + labelEntity + "</div><div style=\"width:130px;display:inline-block;\">" + labelEntityDesc + "</div><div style=\"width:130px;display:inline-block;text-align:right;\">" + labelEntityType + "</div></div>")                           
                   .appendTo($li);

        return $li;
    };
        },

        autocompleteComboBox: function () {
            $.widget("custom.combobox", {
                _create: function () {
                    this.wrapper = $("<span>")
                      .addClass("custom-combobox")
                      .insertAfter(this.element);

                    this.element.hide();
                    this._createAutocomplete();
                    this._createShowAllButton();
                },

                _createAutocomplete: function () {
                    var selected = this.element.children(":selected"),
                      value = selected.val() ? selected.text() : "";

                    this.input = $("<input>")
                      .appendTo(this.wrapper)
                      .val(value)
                      .attr("title", "")
                      .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
                      .autocomplete({
                          delay: 0,
                          minLength: 0,
                          source: $.proxy(this, "_source")
                      })
                      .tooltip({
                          tooltipClass: "ui-state-highlight"
                      });

                    this._on(this.input, {
                        autocompleteselect: function (event, ui) {
                            ui.item.option.selected = true;
                            this._trigger("select", event, {
                                item: ui.item.option
                            });
                        },

                        autocompletechange: "_removeIfInvalid"
                    });
                },

                _createShowAllButton: function () {
                    var input = this.input,
                      wasOpen = false;

                    $("<a>")
                      .attr("tabIndex", -1)
                      .attr("title", "Show All Items")
                      .tooltip()
                      .appendTo(this.wrapper)
                      .button({
                          icons: {
                              primary: "ui-icon-triangle-1-s"
                          },
                          text: false
                      })
                      .removeClass("ui-corner-all")
                      .addClass("custom-combobox-toggle ui-corner-right")
                      .mousedown(function () {
                          wasOpen = input.autocomplete("widget").is(":visible");
                      })
                      .click(function () {
                          input.focus();

                          // Close if already visible
                          if (wasOpen) {
                              return;
                          }

                          // Pass empty string as value to search for, displaying all results
                          input.autocomplete("search", "");
                      });
                },

                _source: function (request, response) {
                    var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                    response(this.element.children("option").map(function () {
                        var text = $(this).text();
                        if (this.value && (!request.term || matcher.test(text)))
                            return {
                                label: text,
                                value: text,
                                option: this
                            };
                    }));
                },

                _removeIfInvalid: function (event, ui) {

                    // Selected an item, nothing to do
                    if (ui.item) {
                        return;
                    }

                    // Search for a match (case-insensitive)
                    var value = this.input.val(),
                      valueLowerCase = value.toLowerCase(),
                      valid = false;
                    this.element.children("option").each(function () {
                        if ($(this).text().toLowerCase() === valueLowerCase) {
                            this.selected = valid = true;
                            return false;
                        }
                    });

                    // Found a match, nothing to do
                    if (valid) {
                        return;
                    }

                    // Remove invalid value
                    this.input
                      .val("")
                      .attr("title", value + " didn't match any item")
                      .tooltip("open");
                    this.element.val("");
                    this._delay(function () {
                        this.input.tooltip("close").attr("title", "");
                    }, 2500);
                    this.input.autocomplete("instance").term = "";
                },

                _destroy: function () {
                    this.wrapper.remove();
                    this.element.show();
                }
            });
        },

        createComboBox: function () {
            $("#entityType").combobox({ select: function (event, ui) { Home.onDropDownChange(); }});
            $("#currency").combobox({ select: function (event, ui) { Home.onDropDownChange(); } });
            $("#country").combobox({ select: function (event, ui) { Home.onDropDownChange(); } });
            $("#managedBy").combobox({ select: function (event, ui) { Home.onDropDownChange(); } });

            $("#opTarget").combobox({ select: function (event, ui) { Home.onDropDownChange(); } });
            $("#investmentDesk").combobox({ select: function (event, ui) { Home.onDropDownChange(); } });
            $("#dataLoadType").combobox({ select: function (event, ui) { Home.onDropDownChange(); } });
            $("#assetClass").combobox({ select: function (event, ui) { Home.onDropDownChange(); } });
            $("#latestData").combobox({ select: function (event, ui) { Home.onDropDownChange(); } });
            $("#contains").combobox();
            $("#partOfGroup").combobox();
            $("#approvedDate").kendoDatePicker({
                format: "yyyy-MM-dd"
            });
            $("#latestDataDate").kendoDatePicker({ format: "yyyy-MM-dd" });
        },
        onDropDownChange: function () {
            Home.showProgress();
            var entity, currency, country, managedBy, investmentDesk, dataLoad, approvedDate, latestDataDate, contains, partOfGroup = null;
            if ($("#entityType").val() == undefined || $("#entityType").val() == -1)
            {
                entity = null;
            }
            else
            {
                entity = $("#entityType").val();
            }
            if ($("#currency").val() == undefined || $("#currency").val() == -1) {
                entity = null;
            }
            else {
                currency = $("#currency").val();
            }
            if ($("#country").val() == undefined || $("#country").val() == -1) {
                country = null;
            }
            else {
                country = $("#country").val();
            }
            if ($("#managedBy").val() == undefined || $("#managedBy").val() == -1) {
                managedBy = null;
            }
            else {
                managedBy = $("#managedBy").val();
            }
            if ($("#investmentDesk").val() == undefined || $("#investmentDesk").val() == -1) {
                investmentDesk = null;
            }
            else {
                investmentDesk = $("#investmentDesk").val();
            }
            if ($("#dataLoadType").val() == undefined || $("#dataLoadType").val() == -1) {
                dataLoad = null;
            }
            else {
                dataLoad = $("#dataLoadType").val();
            }
            approvedDate = $("#approvedDate").data("kendoDatePicker").value();
            latestDataDate = $("#latestDataDate").data("kendoDatePicker").value();

            if ($("#searchContains").val() == undefined || $("#searchContains").val() == -1) {
                contains = null;
            }
            else {
                contains = $("#searchContains").val();
            }
            if ($("#partOfGroup").val() == undefined || $("#partOfGroup").val() == -1) {
                partOfGroup = null;
            }
            else {
                partOfGroup = $("#partOfGroup").val();
            }
            var grid = $("#grid").data('kendoGrid');
            $.ajax({
                url: "SearchPortfolio",
                type: "POST",
                dataType: "json",
                data: {
                    EntityType: entity,
                    Currency: currency,
                    Country: country,
                    ManagedBy: managedBy,
                    InvestmentDesk: investmentDesk,
                    DataLoad: dataLoad,
                    ApprovedDate: approvedDate,
                    LatestData: latestDataDate,
                    Contains: contains,
                    PartOfGroup: partOfGroup
                },
                success: function (data) {
                    Home.hideProgress();
                    grid.dataSource.data(data);
                    grid.refresh();
                    var count = grid.dataSource.total();
                    if(count > 0)
                    {
                        $("#gridRowCount").text("Results(" + count + ")");
                        $("#contentbar").show();
                    }
                    else
                    {
                        $("#contentbar").hide();
                        $("#rightbar").hide();
                        $("#viewPortfolioContainer").hide();
                        $("#viewPortfolio").css({ 'margin-top': '500px' });
                    }
                }
            })
           
        },

        createKendoWindow: function () {
            $("#createNewPortofolioWindow").append("<div id=\"testWindow\"></div>");
            $('#testWindow').kendoWindow({
                title: "Create Portfolio",
                modal: true,
                resizable: false,
                width: 380,
                content: "CreatePortfolio",
                visible: false,
                minHeight: 450,
                animation: {
                    open: {
                        effects: "expandVertical",
                        duration: 1000
                    },
                },
                close: function () {
                    setTimeout(function () {
                        $('#testWindow').kendoWindow('destroy');
                    }, 200);
                }
            }).data('kendoWindow').center().open();
        },

        createPortfolioComboBox: function () {

            $("#Currency").combobox({});
            $("#Country").combobox({  });
            $("#FundManager").combobox({ });
            $("#InvestmentDesk").combobox({  });
            $("#DataLoadType").combobox({  });
            $("#AssetClass").combobox({});

            $("#benchmarkDate").kendoDatePicker({ format: "yyyy-MM-dd" });
            $("#startDate").kendoDatePicker({ format: "yyyy-MM-dd" });
            Home.notification = $("#notification").kendoNotification({
                appendTo:"#notification",
                autoHideAfter: 0,
                button: false,
                templates: [{ type: "error", template: $("#errorTemplate").html() }]
            }).data("kendoNotification");
        },
        searchContains: function () {
            $("#searchContains").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "GetEntities",
                        type: "POST",
                        dataType: "json",
                        data: { "request": request.term },
                        success: function (data) {
                            response($.map(data, function (item) {
                                return { label: item, value: item.Entity };
                            }))

                        }
                    })
                }
            }).data("ui-autocomplete")._renderItem = function (ul, item) {
                var re = new RegExp("(" + this.term + ")", "gi"),
                                cls = "search-text-highlight",
                               template = "<span class='" + cls + "'>$1</span>";
                var labelEntity = item.label.Entity.replace(re, template);
                var $li = $("<li/>").appendTo(ul);

                $("<a/>").attr("href", "#")
                           .html("<div style=\"width:330px;\"><div style=\"width:70px;display:inline-block;text-align:top;\">" + labelEntity + "</div>" + "</div></div>")
                           .appendTo($li);

                return $li;
            };
        },

        createPortFolio: function () {
            var portfolio = new Object();
            portfolio.Name = $("#Name").val();
            portfolio.Code = $("#Code").val();
            portfolio.Currency = $("#Currency").val();
            portfolio.Country = $("#Country").val();
            portfolio.FundManager = $("#FundManager").val();
            portfolio.AssetClass = $("#AssetClass").val();
            portfolio.InvestmentDesk = $("#InvestmentDesk").val();
            portfolio.DataLoadType = $("#DataLoadType").val();
            portfolio.OutputTarget = $("#OutputTarget").val();
            portfolio.StartDate = $("#startDate").data("kendoDatePicker").value();
            portfolio.BenchmarkDate = $("#benchmarkDate").data("kendoDatePicker").value();
            portfolio.portfolioCheck = $("#Sub-Portfolio").is(":checked");
            portfolio.portfolioType = "Sub-Portfolio";
            
            var isTrue = true;
            var errors = new Array();
            if (portfolio.Name == "")
            {
                errors.push(["Name is mandatory"]);
                isTrue = false;
            }
            if (portfolio.Code == "") {
                errors.push(["Code is mandatory"]);
                isTrue = false;
            }
            if (portfolio.Currency == "") {
                errors.push(["Currency is mandatory"]);
                isTrue = false;
            }
            if (portfolio.Country == "") {
                errors.push(["Country is mandatory"]);
                isTrue = false;
            }
            if (portfolio.FundManager == "") {
                errors.push(["Fund Manager is mandatory"]);
                isTrue = false;
            }
            if (portfolio.AssetClass == "") {
                errors.push(["Asset Class is mandatory"]);
                isTrue = false;
            }
            if (portfolio.InvestmentDesk == "") {
                errors.push(["Investment Desk is mandatory"]);
                isTrue = false;
            }
            if (portfolio.DataLoadType == "") {
                errors.push(["Data Load Type is mandatory"]);
                isTrue = false;
            }
            if (portfolio.OutputTarget == "") {
                errors.push(["Output Target is mandatory"]);
                isTrue = false;
            }
            if (portfolio.StartDate == "") {
                errors.push(["Start Date is mandatory"]);
                isTrue = false;
            }
            if (portfolio.BenchmarkDate == "") {
                errors.push(["Benchmark Date is mandatory"]);
                isTrue = false;
            }
            if (!portfolio.portfolioCheck)
            {
                errors.push(["Type is not Checked"]);
                isTrue = false;
            }
            var values = JSON.stringify(portfolio);
            if (isTrue)
            {
                $.ajax({
                    url: "AddPortfolio",
                    type: "POST",
                    dataType: "json",
                    data: {
                        portfolio: values
                    },
                    success: function (data) {
                        if (data.Success)
                        {
                            Home.onCancelClick();
                            Home.createKendoWindowNoTitle("Portfolio Created Successfully");
                        }
                        else
                        {
                            Home.notification.error({ message: data.Message }, "error");
                            var container = $(Home.notification.options.appendTo);
                            container.scrollTop(container[0].scrollHeight);
                        }
                    }
                })
            }
            else {
                if (Home.notification != null)
                {
                    Home.notification.hide();
                    var message = null;
                    $.each(errors, function (index, value) {
                        Home.notification.error({ message: value }, "error");
                    });
                    var container = $(Home.notification.options.appendTo);
                    container.scrollTop(container[0].scrollHeight);
                }                
            }
           
        },

        resizegrid: function () {
            var gridElement = $("#grid"),
            dataArea = gridElement.find(".k-grid-content"),
            gridHeight = gridElement.innerHeight()-160,
            otherElements = gridElement.children().not(".k-grid-content"),
            otherElementsHeight = 0;
            otherElements.each(function () {
                otherElementsHeight += $(this).outerHeight();
            });
            dataArea.height(gridHeight - otherElementsHeight);
        },
        onOkClick: function () {
            $('#userMessageWindow').kendoWindow('destroy');
            Home.onDropDownChange();
        },
        onCancelClick: function () {
            $('#testWindow').kendoWindow('destroy');
        },
        createKendoWindowNoTitle: function (message) {
            $("#window").append("<div id=\"userMessageWindow\"></div>");
            var window = $("#userMessageWindow");
           window.kendoWindow({
               width: "220px",
               height: "80px",
               title: false,
               modal: true,
               resizable: false,
               actions: [],
               content: "UserResponse?message="+message
           }).data('kendoWindow').center().open();


        },

        showProgress: function () {
            kendo.ui.progress($("#contentDetails"), true);
        },
        hideProgress : function()
        {
            kendo.ui.progress($("#contentDetails"), false);
        }
    };
}();